package sz.szsmk.citizencard.widget;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;


import com.google.zxing.client.android.Intents;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by psylife00 on 2017/11/7.
 */

public class MyCaptureManager extends CaptureManager {
    private static final String TAG = MyCaptureManager.class.getSimpleName();
    Activity activity;
    private boolean returnBarcodeImagePath = false;
    Bundle bundle;

    public void setBundle(Bundle bundle) {
        this.bundle = bundle;
    }

    public MyCaptureManager(Activity activity, DecoratedBarcodeView barcodeView) {
        super(activity, barcodeView);
        this.activity = activity;
    }
    protected void returnResult(BarcodeResult rawResult) {
        Intent intent = resultIntent(rawResult, getBarcodeImagePath(rawResult));
        if(this.bundle!=null){
            intent.putExtra("bundle",bundle);
        }

        //回调 到 扫描
        if(onScanResult!=null){
            onScanResult.onScanResult(intent);
        }

    }

    public void closeAndFinish(){



        super.closeAndFinish();
    }


    public void isreturnBarcodeImagePath(Intent intent){
        if(intent != null) {

            if (intent.getBooleanExtra(Intents.Scan.BARCODE_IMAGE_ENABLED, false)) {
                returnBarcodeImagePath = true;
            }
        }
    }


    private String getBarcodeImagePath(BarcodeResult rawResult) {
        String barcodeImagePath = null;
        if (returnBarcodeImagePath) {
            Bitmap bmp = rawResult.getBitmap();
            try {
                File bitmapFile = File.createTempFile("barcodeimage", ".jpg", activity.getCacheDir());
                FileOutputStream outputStream = new FileOutputStream(bitmapFile);
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                outputStream.close();
                barcodeImagePath = bitmapFile.getAbsolutePath();
            } catch (IOException e) {
                Log.w(TAG, "Unable to create temporary file and store bitmap! " + e);
            }
        }
        return barcodeImagePath;
    }


    public interface OnScanResult{
        void onScanResult(Intent intent);
    }

    OnScanResult onScanResult;

    public OnScanResult getOnScanResult() {
        return onScanResult;
    }

    public void setOnScanResult(OnScanResult onScanResult) {
        this.onScanResult = onScanResult;
    }
}
